<template>
  <div class="publish-container">
    <el-card class="publish-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">编辑商品</h1>
        </div>
      </template>

      <el-form 
        :model="product" 
        :rules="rules" 
        ref="productForm"
        label-position="top"
        @submit.prevent="submitProduct"
      >
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="product.name"
            placeholder="请输入商品名称"
            clearable
            :prefix-icon="Goods"
          />
        </el-form-item>

        <!-- 商品分类 -->
        <el-form-item label="商品分类" prop="category">
          <el-cascader
            v-model="product.category"
            :options="categoryOptions"
            placeholder="请选择商品分类"
            :props="{ expandTrigger: 'hover', checkStrictly: true }"
            clearable
            style="width: 100%"
          />
        </el-form-item>

        <!-- 商品图片上传 -->
        <el-form-item label="商品图片 (最多9张)" prop="images">
          <el-upload
            :file-list="product.fileList"
            @change="handleFileChange"
            @remove="handleRemove"
            action="#"
            list-type="picture-card"
            :multiple="true"
            :limit="9"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            accept="image/*"
            class="image-uploader"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                点击上传图片，支持JPG/PNG格式，单张不超过5MB
              </div>
            </template>
          </el-upload>
          
          <el-dialog v-model="dialogVisible" width="70%">
            <img w-full :src="dialogImageUrl" alt="预览图片" style="max-height: 70vh; object-fit: contain;" />
          </el-dialog>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="product.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品详细描述"
            maxlength="500"
            show-word-limit
            resize="none"
          />
        </el-form-item>

        <!-- 价格设置 -->
        <el-form-item label="价格设置" prop="price">
        <el-input
    v-model="priceInput"
    placeholder="请输入商品价格"
    clearable
    @input="formatPrice"
  >
    <template #prefix>
      <span style="color: #666">¥</span>
    </template>
    <template #append>
      <span>元</span>
    </template>
  </el-input>
        </el-form-item>

        <!-- 发货地 -->
    <el-form-item label="发货地" prop="delivery_location">
      <el-cascader
        v-model="product.delivery_location"
        :options="locationOptions"
        placeholder="请选择发货地"
        :props="{ expandTrigger: 'hover' }"
        clearable
        style="width: 100%"
      />
    </el-form-item>

        <!-- 发货方式 -->
        <el-form-item label="发货方式" prop="delivery_method">
          <el-select
            v-model="product.delivery_method"
            placeholder="请选择发货方式"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="method in shippingMethods"
              :key="method.value"
              :label="method.label"
              :value="method.value"
            />
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            class="submit-btn"
            :loading="isSubmitting"
          >
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Goods, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/utils/request'
const route = useRoute()
const productCode = route.query.product_code

// 表单数据
const product = reactive({
  name: '',
  category: [], // 改为数组格式，与发布表单一致
  fileList: [],
  description: '',
  price: 0,
  delivery_location: [],
  delivery_method: null,
  images: [],
  deletedImages: [] // 新增：存储被删除的图片ID
})

// 价格输入框的双向绑定
const priceInput = ref('')

// 商品分类选项
const categoryOptions = ref([])

// 发货地选项
const locationOptions = ref([
  {
    value: 'a-campus',
    label: 'A校区',
    children: [
      { value: 'main-building', label: '主教学楼' },
      { value: 'north-dorm', label: '北苑宿舍区' },
      { value: 'south-gate', label: '南门快递点' }
    ]
  },
  {
    value: 'b-campus',
    label: 'B校区',
    children: [
      { value: 'library', label: '图书馆' },
      { value: 'sports-center', label: '体育中心' },
      { value: 'west-canteen', label: '西区食堂' }
    ]
  },
  {
    value: 'c-campus',
    label: 'C校区',
    children: [
      { value: 'lab-building', label: '实验楼区' },
      { value: 'east-garden', label: '东花园' },
      { value: 'tech-park', label: '科技园区' }
    ]
  }
])
// 发货方式选项
const shippingMethods = ref([
  { value: 0, label: '包邮' },
  { value: 1, label: '按距离计费' },
  { value: 2, label: '一口价' },
  { value: 3, label: '无需邮寄' }
])

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
  ],
  category: [
    { 
      validator: (rule, value, callback) => {
        if (!value || value.length !== 2) {
          callback(new Error('请选择完整的商品分类'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 5, message: '至少输入5个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (isNaN(value) || value <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  delivery_location: [
    { 
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择发货地'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  delivery_method: [
    { required: true, message: '请选择发货方式', trigger: 'change' }
  ]
})

const productForm = ref(null)
const isSubmitting = ref(false)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 监听priceInput变化，同步到product.price
watch(priceInput, (newVal) => {
  if (newVal === '') {
    product.price = 0
  } else {
    product.price = parseFloat(newVal)
  }
})

// 格式化价格输入
const formatPrice = () => {
  let value = priceInput.value.trim()
  value = value.replace(/[^0-9.]/g, '')
  
  const decimalCount = (value.match(/\./g) || []).length
  if (decimalCount > 1) {
    const firstDotIndex = value.indexOf('.')
    value = value.substring(0, firstDotIndex + 1) + value.substring(firstDotIndex + 1).replace(/\./g, '')
  }
  
  const parts = value.split('.')
  if (parts.length > 1) {
    if (parts[1].length > 2) {
      parts[1] = parts[1].substring(0, 2)
    }
    
    if (parts[1].length === 0) {
      value = parts[0] + '.'
    } else {
      value = parts.join('.')
    }
  }
  
  if (value.startsWith('.')) {
    value = '0' + value
  }
  
  if (value.length > 10) {
    value = value.substring(0, 10)
  }
  
  if (value === '0') {
    value = ''
  }
  
  priceInput.value = value
}

// 处理API返回的分类数据
const processCategories = (categories) => {
  return categories
    .filter(cat => cat.children && cat.children.length > 0)
    .map(root => ({
      value: root.id,
      label: root.display_name,
      children: root.children.map(child => ({
        value: child.id,
        label: child.display_name,
      }))
    }))
}

// 获取分类数据并处理
const fetchAndProcessCategories = async () => {
  try {
    const cachedCategories = localStorage.getItem('cachedCategories')
    if (cachedCategories) {
      categoryOptions.value = JSON.parse(cachedCategories)
      return
    }

    const response = await apiClient.get('/api/products/categories/choices/')
    
    if (response.data && Array.isArray(response.data)) {
      const processedCategories = processCategories(response.data)
      categoryOptions.value = processedCategories
      localStorage.setItem('cachedCategories', JSON.stringify(processedCategories))
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败，请稍后重试')
  }
}

// 解析发货地址
const parseDeliveryLocation = (locationStr) => {
  if (!locationStr) return []
  
  // 尝试按空格分割
  const parts = locationStr.split(/\s+/)
  if (parts.length >= 2) {
    return [parts[0].replace('市', ''), parts[1].replace('区', '').replace('县', '')]
  }
  
  // 尝试按逗号分割
  const commaParts = locationStr.split(',')
  if (commaParts.length >= 2) {
    return [commaParts[0].replace('市', ''), commaParts[1].replace('区', '').replace('县', '')]
  }
  
  return []
}

const getFullImageUrl = (path) => {
  if (!path) return ''
  
  if (path.startsWith('http')) {
    return path
  }
  
  const domain = 'http://swk1m10at.hd-bkt.clouddn.com'
  // 清理路径中的多余斜杠
  const cleanPath = path.replace(/^\/+/, '')
  return `${domain}/${cleanPath}`
}

// 获取商品详情
const fetchProductDetails = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const response = await apiClient.get(`/api/products/seller/${productCode}/`)

    if (response.data) {
      const data = response.data
      
      // 填充表单数据
      product.name = data.name
      product.description = data.description || ''
      product.price = data.price
      priceInput.value = data.price.toString()
      product.delivery_method = data.delivery_method
      
      // 处理发货地址
      product.delivery_location = parseDeliveryLocation(data.delivery_location)
      
      // 处理分类 - 需要找到对应的父分类ID
      if (data.category) {
        const allCategories = categoryOptions.value.flatMap(cat => 
          cat.children.map(child => ({
            id: child.value,
            parentId: cat.value,
            label: `${cat.label}/${child.label}`
          }))
        )
        
        const foundCategory = allCategories.find(c => c.id === data.category)
        if (foundCategory) {
          product.category = [foundCategory.parentId, foundCategory.id]
        }
      }
      
      // 处理图片 - 修复图片加载问题
      if (data.images && data.images.length > 0) {
        product.images = data.images
        product.fileList = data.images.map(img => ({
          id: img.id, // 保存图片ID以便后续删除
          url: getFullImageUrl(img.url || img.image_url), // 修复图片URL获取方式
          name: (img.url || img.image_url)?.split('/').pop() || 'product_image',
          status: 'success'
        }))
      }
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败，请稍后重试')
    if (error.response?.status === 401) {
      localStorage.removeItem('access_token')
      window.location.href = '/login'
    } else if (error.response?.status === 404) {
      ElMessage.error('商品不存在')
      window.location.href = '/Mine/fabu'
    }
  }
}

// 处理文件变化
const handleFileChange = (uploadFile, fileList) => {
  product.fileList = fileList
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  
  if (product.fileList.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  
  return true
}

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url || file.response?.data?.url || ''
  dialogVisible.value = true
}

// 移除图片
const handleRemove = (file, fileList) => {
  // 记录被删除的已有图片ID
  if (file.id && !product.deletedImages.includes(file.id)) {
    product.deletedImages.push(file.id);
    console.log('记录删除图片ID:', file.id); // 调试用
  }
  product.fileList = fileList;
};

// 提交表单
const submitProduct = async () => {
  try {
    isSubmitting.value = true;
    await productForm.value.validate();

    const token = localStorage.getItem('access_token');
    if (!token) throw new Error('请先登录');

    // 1. 准备FormData
    const formData = new FormData();
    
    // 2. 添加基本商品信息
    formData.append('name', product.name);
    formData.append('price', product.price);
    formData.append('category', product.category[1]);
    formData.append('description', product.description);
    formData.append('delivery_method', product.delivery_method);
    formData.append('delivery_location', product.delivery_location.join(' '));

    // 3. 关键修改：添加删除的图片ID
    if (product.deletedImages.length > 0) {
      product.deletedImages.forEach(id => {
  formData.append('deleted_images', id);
});
    }

    // 4. 添加新上传的图片
    const newImages = product.fileList.filter(file => file.raw);
    newImages.forEach(file => {
      formData.append('images', file.raw);
    });

    // 5. 发送请求
    const response = await apiClient.put(
      `/api/products/seller/${productCode}/`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    );

    // 6. 处理响应
    if (response.data?.images) {
      // 更新本地图片列表
      product.fileList = response.data.images.map(img => ({
        id: img.id,
        url: getFullImageUrl(img.url || img.image_url),
        name: (img.url || img.image_url)?.split('/').pop() || 'product_image',
        status: 'success'
      }));
      product.deletedImages = []; // 清空删除记录
    }

    ElMessage.success('商品更新成功！');
    setTimeout(() => window.location.href = '/Mine/fabu', 1500);
  } catch (error) {
  
    ElMessage.error(`更新失败: ${error.response?.data?.error || error.message}`);
  } finally {
    isSubmitting.value = false;
  }
};
// 初始化加载
onMounted(async () => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessageBox.confirm(
      '您尚未登录，无法编辑商品。是否前往登录页面？',
      '提示',
      {
        confirmButtonText: '前往登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      window.location.href = '/login'
    }).catch(() => {})
    return
  }
  
  if (!productCode) {
    ElMessage.error('缺少商品编码参数')
    window.location.href = '/Mine/fabu'
    return
  }

  // 先获取分类数据，再获取商品详情
  await fetchAndProcessCategories()
  await fetchProductDetails()
})
</script>

<style scoped>
.publish-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.publish-card {
  width: 100%;
  max-width: 800px;
  border-radius: 12px;
}

.card-header {
  text-align: center;
}

.card-header .title {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 24px;
}

.image-uploader {
  width: 100%;
}

:deep(.el-upload-list__item) {
  transition: all 0.3s;
}

:deep(.el-upload-list__item:hover) {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  margin-top: 20px;
}
</style>